//
//  AY_BookDetailViewController.m
//  AiYue
//
//  Created by mac on 2023/10/24.
//

#import "AY_BookDetailViewController.h"
#import "AY_DetailHeaderView1.h"
#import "AY_DetailIntroCell.h"
#import "AY_DetailContentCell.h"
#import "AY_DetailRecommendCell.h"

@interface AY_BookDetailViewController ()<SXLoadingDelegate>
@property (nonatomic, strong) AY_DetailHeaderView1 *headerView;
@property (nonatomic,assign) float headerViewHeight;
@property (nonatomic, strong) BookModel *bookModel;
@property (nonatomic, strong) UIView *bottomView;
@property (nonatomic, strong) YButton *addBook;
@property (nonatomic, strong) NSArray *recommendList;
@property (strong,nonatomic) AY_LoadingView *loadingView;

@end

@implementation AY_BookDetailViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self getBookCaseInfo];
}

- (void)getBookCaseInfo {
    [AYApiRequest getBookDetailWithBookId:self.bookId Success:^(AY_BookDetailModel * _Nonnull pkg) {
        self.bookModel = pkg.data;
        if ([self.bookModel.shelfFlag isEqual:@"1"]) {
            self.addBook.selected = YES;
            [self.addBook setTitle:@"已在书架" forState:UIControlStateNormal];
        }else {
            self.addBook.selected = NO;
            [self.addBook setTitle:@"加入书架" forState:UIControlStateNormal];
        }
        
    } failure:^(int status, NSString * _Nonnull info) {
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setup];
}

- (void)setup {
    self.gk_navTitle = @"书籍详情";
    self.gk_navBackgroundColor = COLOR_Bg;
    [self.tableView registerClass:[AY_DetailContentCell class] forCellReuseIdentifier:@"AY_DetailContentCell"];
    self.gk_navLeftBarButtonItem = [UIBarButtonItem itemWithImageName:@"AY_nav_pop" target:self action:@selector(popVC)];
    self.tableView.frame = CGRectMake(0, GK_STATUSBAR_NAVBAR_HEIGHT, SCREEN_W, SCREEN_H - GK_TABBAR_HEIGHT - GK_STATUSBAR_NAVBAR_HEIGHT - YNUM(1));
    self.view.backgroundColor = COLOR(@"#F6F7FB");
    self.tableView.backgroundColor = COLOR(@"#F6F7FB");
    self.tableView.tableHeaderView = self.headerView;
    
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.bottomView];
    [self getData];

}

-(void)popVC{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)setBookId:(NSString *)bookId {
    _bookId = bookId;
}

- (void)getData {
    [self.loadingView loadingInView:self.view];
    dispatch_group_t group = dispatch_group_create();
    
    dispatch_group_enter(group);
    [AYApiRequest getBookDetailWithBookId:self.bookId Success:^(AY_BookDetailModel * _Nonnull pkg) {
        dispatch_group_leave(group);
        self.bookModel = pkg.data;
        self.headerView.bookModel = pkg.data;
        if ([self.bookModel.shelfFlag isEqual:@"1"]) {
            self.addBook.selected = YES;
            [self.addBook setTitle:@"已在书架" forState:UIControlStateNormal];
        }else {
            self.addBook.selected = NO;
            [self.addBook setTitle:@"加入书架" forState:UIControlStateNormal];
        }
    } failure:^(int status, NSString * _Nonnull info) {
        dispatch_group_leave(group);
        [self.loadingView refresh];
    }];
    
    dispatch_group_enter(group);
    [AYApiRequest getBookRecommendListWithArticleId:self.bookId andLimit:@"8" Success:^(AY_AudioBookModel * _Nonnull pkg) {
        dispatch_group_leave(group);
        if([pkg.code isEqualToString:@"200"]) {
            self.recommendList = [NSMutableArray arrayWithArray:pkg.data];
        }
    } failure:^(int status, NSString * _Nonnull info) {
        dispatch_group_leave(group);
        [self.loadingView refresh];
    }];
    
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        [self.loadingView dismiss];
        [self.tableView reloadData];
    });
}

- (void)changeData {
    [AYApiRequest getBookRecommendListWithArticleId:self.bookId andLimit:@"8" Success:^(AY_AudioBookModel * _Nonnull pkg) {
        if([pkg.code isEqualToString:@"200"]) {
            self.recommendList = [NSMutableArray arrayWithArray:pkg.data];
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:2 inSection:0];
            [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
        }
    } failure:^(int status, NSString * _Nonnull info) {
    }];
}

- (NSArray *)recommendList {
    if(!_recommendList) {
        _recommendList = [NSArray array];
    }
    return _recommendList;
}

- (AY_LoadingView *)loadingView {
    if (!_loadingView) {
        _loadingView = [[AY_LoadingView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, SCREEN_H)];
        _loadingView.backgroundColor = COLOR(@"#F7F5F6");
        _loadingView.delegate = self;
        _loadingView.hideLeftpop = NO;
    }
    return _loadingView;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 3;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        static NSString *ID = @"AY_DetailIntroCell";
        AY_DetailIntroCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
        if (cell == nil) {
            cell = [[AY_DetailIntroCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.bookModel = self.bookModel;
        return cell;
    }else if (indexPath.row == 1) {
        static NSString *ID = @"AY_DetailContentCell";
        AY_DetailContentCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
        if (cell == nil) {
            cell = [[AY_DetailContentCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.bookModel = self.bookModel;
        Weak_Self
        cell.goReadBlock = ^{
            AY_PageReadViewController *vc = [[AY_PageReadViewController alloc] init];
            AY_ReadBookModel *model = [AYTool getBookDataWithBookId:weakSelf.bookId];
            [vc sendBookId:weakSelf.bookId andPage:model.page andChapterIndex:model.chapterIndex];
            [weakSelf.navigationController pushViewController:vc animated:YES];
        };
        return cell;
    }else {
        static NSString *ID = @"AY_DetailRecommendCell";
        AY_DetailRecommendCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
        if (cell == nil) {
            cell = [[AY_DetailRecommendCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
        }
        cell.recommendList = self.recommendList;
        Weak_Self
        cell.recommendBlock = ^{
            [weakSelf changeData];
        };
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        return [self.bookModel.status isEqual:@"2"] ? YNUM(65) : YNUM(320);
    }else if (indexPath.row == 1) {
        return [self.tableView fd_heightForCellWithIdentifier:@"AY_DetailContentCell" configuration:^(id cell) {
            [self setupOfCell:cell atIndexPath:indexPath];
        }];
    }else {
        if (self.recommendList.count > 4) {
            return YNUM(259) + YNUM(125);
        }else if (self.recommendList.count == 0) {
            return 0.001;
        }else {
            return YNUM(259);
        }
    }
}

#pragma mark - 阅读
- (void)goRead:(UIButton *)btn {
    AY_PageReadViewController *vc = [[AY_PageReadViewController alloc] init];
    AY_ReadBookModel *model = [AYTool getBookDataWithBookId:self.bookId];
    [vc sendBookId:self.bookId andPage:model.page andChapterIndex:model.chapterIndex];
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - 添加书架
- (void)addBook:(UIButton *)btn {
    if (!self.addBook.selected) {
        [AYApiRequest addBookWithBookId:self.bookId andChapterNo:@"0" andPageNo:@"0" Success:^(AY_BaseModel * _Nonnull pkg) {
            ShowToast(@"添加书架成功");
            self.addBook.selected = YES;
            [self.addBook setTitle:@"已在书架" forState:UIControlStateNormal];
        } failure:^(int status, NSString * _Nonnull info) {
            
        }];
    }
}

- (void)setupOfCell:(AY_DetailContentCell *)cell atIndexPath:(NSIndexPath *)indexPath {
    cell.bookModel = self.bookModel;
}

- (AY_DetailHeaderView1 *)headerView {
    if (!_headerView) {
        _headerView = [[AY_DetailHeaderView1 alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, YNUM(267))];
    }
    return _headerView;
}

- (UIView *)bottomView {
    if (!_bottomView) {
        _bottomView = [AYTool createViewWithFrame:CGRectMake(0, SCREEN_H - GK_TABBAR_HEIGHT, SCREEN_W, GK_TABBAR_HEIGHT) andBg:nil andRadius:0 andAddSubView:self.view];
        _bottomView.backgroundColor =  [UIColor whiteColor];
        self.addBook = [[YButton alloc] initWithFrame:CGRectMake(YNUM(40), 0, YNUM(58), YNUM(90))];
        [self.addBook centerImageAndTitle:YNUM(8)];
        self.addBook.titleLabel.font = YFont(12);
        [self.addBook addTarget:self action:@selector(addBook:) forControlEvents:UIControlEventTouchUpInside];
        [self.addBook setTitleColor:COLOR(@"#000002") forState:UIControlStateNormal];
        [self.addBook setImage:YImage(@"AY_bookdetail_add") forState:UIControlStateNormal];
        [_bottomView addSubview:self.addBook];
        
        UIButton *readBtn = [AYTool createButtonWithFrame:CGRectMake(SCREEN_W - YNUM(252), YNUM(12), YNUM(240), YNUM(45)) andTitle:nil andFont:nil andTitleColor:nil andBg:THEME_COLOR andImage:nil andBgImage:nil andTarget:self andAction:@selector(goRead:) andRadius:YNUM(22) andAddSubView:_bottomView];
        UILabel *read = [AYTool createLabelWithFrame:CGRectZero andText:@"立即阅读" andTextColor:[UIColor whiteColor] andBgColor:nil andFont:[UIFont boldSystemFontOfSize:YNUM(16)] andLines:1 andRadius:0 andAddSubView:readBtn];
        [read mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.centerY.equalTo(readBtn);
        }];
        [readBtn setBackgroundImage:[AYTool buttonImageFromColor:COLOR(@"dc5919")] forState:UIControlStateHighlighted];
        readBtn.titleLabel.font = YFont(15);
    }
    return _bottomView;
}

- (void)refreshAction {
    [self getData];
}

- (void)popAction {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)dealloc {
    self.headerView.timer = nil;
    [self.headerView.timer invalidate];
}
@end
